package cc.rengu.igas.channel.alipay.core.packswitch;

import cc.rengu.igas.channel.alipay.common.constant.AlipayConfigConstant;
import cc.rengu.igas.channel.alipay.common.constant.AlipayParamConstant;
import cc.rengu.igas.channel.alipay.common.constant.AlipayTreeNodeConstant;
import cc.rengu.igas.channel.alipay.common.constant.AlipayTxnNumConstant;
import cc.rengu.jradp.mods.message.MessageTree;
import cc.rengu.jradp.packetswitch.IncomingPackSwitchImpl;
import cc.rengu.jradp.packetswitch.OutgoingPackSwitchImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.BizMsgInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.BizMsgInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.BizMsgInfo;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import com.alibaba.fastjson.JSON;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 与支付宝通讯层报文解包前后、组前包后实现类
 * Created by 王成 on 2018/5/31.
 */
public class AlipayNotifyPackSwitch implements IncomingPackSwitchImpl, OutgoingPackSwitchImpl {

    @Override
    public byte[] beforeInComPackSwitch(byte[] bytes) throws Exception {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        Map<String, String> msgMap = new HashMap<>();
        String input = new String(bytes);
        xmlTreeUtil.setXmlTreeStringValue(AlipayTreeNodeConstant.REQUEST_NODE, input);
        String charset;
        if (input.contains("GBK") || input.contains("gbk")) {
            rglog.trace("GBK编码格式...");
            charset = "gbk";
        } else {
            rglog.trace("UTF-8编码格式...");
            charset = "utf-8";
        }
        String noticeBuff = "";
        String[] str = input.split("&", -1);
        for (int i = 0; i < str.length; i++) {
            String[] str1 = str[i].split("=", -1);
            String str2 = URLDecoder.decode(str1[1], charset);
            msgMap.put(str1[0], str2);
            rglog.trace("key:<{}>,value:<{}>", str1[0], str2);
        }
        msgMap.put(TreeNodeConstant.TXN_NUM, "xxxxx");

        rglog.trace("msgMap:<{}>", JSON.toJSONString(msgMap));
        return JSON.toJSONString(msgMap).getBytes();
    }

    @Override
    public int afterInComPackSwitch() throws Exception {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /*根据url服务名转换交易码*/
        String serverUrl = xmlTreeUtil.getXmlTreeStringValue("_MESSAGEHEAD/@server_url");
        int lastIndex = serverUrl.lastIndexOf("/");
        String notifyUrl = serverUrl.substring(0, lastIndex);
        SysParamService sysParamService = new SysParamServiceImpl();
        List<SysParam> sysParamList = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID, AlipayConfigConstant.INST_HOST_URL);
        if (null != sysParamList && sysParamList.size() > 0) {
            Iterator<SysParam> itSysParam = sysParamList.iterator();
            while (itSysParam.hasNext()) {
                SysParam sysParam = itSysParam.next();
                if (notifyUrl.contains(sysParam.getParamValue())) {
                    xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.INST_ID, sysParam.getParamValue());
                    break;
                }
            }
            rglog.error("url<{}>非法通知地址，请联系管理人员!", notifyUrl);
            return -1;
        }
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.INST_ID, AppParamConstant.DEFAULT_INSTID);
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.MSG_SRC_ID, AlipayParamConstant.TUNL_ID_ALIP);
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.BIZ_TYPE, AppParamConstant.DEFAULT_BIZ_TYPE);
        String method = xmlTreeUtil.getXmlTreeStringValue(AlipayTreeNodeConstant.ALI_METHOD);
        if ("ant.merchant.expand.indirect.activity.passed".equals(method) ||
                "ant.merchant.expand.indirect.activity.rejected".equals(method)) {
            xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.SRC_SYS_ID, "BOMP");
            xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, AlipayTxnNumConstant.T00CH301);
        } else {
            rglog.error("暂不支持的通知交易类型<{}>", method);
            return -1;
        }


        MessageTree xmlTree = new MessageTree();
        rglog.trace("tree:<{}>", xmlTree.toString());

        return 0;
    }

    @Override
    public int beforeOutgoPackSwitch() throws Exception {
        return 0;
    }

    @Override
    public byte[] afterOutgoPackSwitch(byte[] bytes) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        return bytes;
    }

    private void updateBizMsgInfo(RgLogger rglog, String bizRspMsg) {
        try {
            XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
            if (bizRspMsg.length() > 8000) {
                rglog.error("存储转发报文超过8K，暂不登记到存储转发表:<{}>", bizRspMsg);
                return;
            }
            if (xmlTreeUtil.isExist(AlipayTreeNodeConstant.ALIP_BIZ_MSG_INFO)) {
                rglog.error("获取请求业务报文节点失败，不更新");
                return;
            }
            BizMsgInfo bizMsgInfo = (BizMsgInfo) xmlTreeUtil.getXmlTreeObjectValue(AlipayTreeNodeConstant.ALIP_BIZ_MSG_INFO, BizMsgInfo.class);
            BizMsgInfoMapper bizMsgInfoMapper = new BizMsgInfoMapperImpl();
            bizMsgInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            if (bizRspMsg.length() < 4000) {
                bizMsgInfo.setBizRspMsg(bizRspMsg);
            } else {
                bizMsgInfo.setBizRspMsg(bizRspMsg.substring(0, 4000));
                bizMsgInfo.setBizRspExpandMsg(bizRspMsg.substring(4000));
            }
            int iReturnCode = bizMsgInfoMapper.updateBizMsgInfoByTransSeqNum(bizMsgInfo);
            if (0 != iReturnCode) {
                return;
            }
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("登记业务报文信息表异常:<{}>", byteArrayOutputStream.toString());
        }
    }
}
